package com.example.demo.Controller;

import com.example.demo.Common.Constants;
import com.example.demo.Common.ResultData;
import com.example.demo.Common.ServiceResultEnum;
import com.example.demo.Config.Annotation.TokenToUser;
import com.example.demo.Entity.Admin;
import com.example.demo.Entity.Customer;
import com.example.demo.Entity.Order;
import com.example.demo.Param.*;
import com.example.demo.Service.UserService;
import com.example.demo.Util.BeanUtil;
import com.example.demo.Util.NumberUtil;
import com.example.demo.Util.Result;
import com.example.demo.Util.ResultGenerator;
import com.example.demo.VO.UserVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class UserController {

    @Resource
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @PostMapping("/user/register")
    @ApiOperation(value = "客户注册", notes = "")
    public Result register(@RequestBody @Valid UserRegisterParam userRegisterParam) {
        if (!NumberUtil.isPhone(userRegisterParam.getTelphone())){
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_IS_NOT_PHONE.getResult());
        }
        String registerResult = userService.registerC(userRegisterParam.getUserName(), userRegisterParam.getTelphone(), userRegisterParam.getPassword());

       // logger.info("register api,loginName={},loginResult={}", userRegisterParam.getLoginName(), registerResult);

        //注册成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(registerResult)) {
            return ResultGenerator.genSuccessResult();
        }
        //注册失败
        return ResultGenerator.genFailResult(registerResult);
    }

    @PostMapping("/user/loginC")
    @ApiOperation(value = "登录接口", notes = "返回token")
    public Result<String> loginC(@RequestBody @Valid UserLoginParam userLoginParam) {
        if (!NumberUtil.isPhone(userLoginParam.getTelphone())){
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_IS_NOT_PHONE.getResult());
        }
        String loginResult = userService.loginC(userLoginParam.getTelphone(), userLoginParam.getPasswordMd5());

        logger.info("login api,telphone={},loginResult={}", userLoginParam.getTelphone(), loginResult);

        //登录成功
        if (!StringUtils.isEmpty(loginResult) && loginResult.length() == Constants.TOKEN_LENGTH) {
            Result result = ResultGenerator.genSuccessResult();
            result.setData(loginResult);
            return result;
        }
        //登录失败
        return ResultGenerator.genFailResult(loginResult);
    }

    @PostMapping("/user/loginA")
    @ApiOperation(value = "登录接口")
    public ResultData loginA(@RequestBody @Valid AdminLoginParam adminLoginParam) {
        Admin admin = new Admin();
        String userName = adminLoginParam.getUserName();
        String userPwd = adminLoginParam.getUserPwd();
        //  System.out.println(userName);
        //  System.out.println(userPwd);
        admin = this.userService.loginA(userName, userPwd);
        //System.out.println(user.getRank());
        if(admin != null){
            log.info("登录成功！");
        }else{
            return ResultData.fail("该系统用户不存在！");
        }
        return ResultData.success(1);
    }

    @GetMapping("/admin/getAll")
    public List<Customer> getAdmins(){
        return this.userService.getAll();
    }

    @PostMapping("/user/logoutA")
    @ApiOperation(value = "系统用户登出接口", notes = "清除token")
    public Result<String> logoutA(@TokenToUser Admin loginAdmin) {
        Boolean logoutResult = userService.logoutA(loginAdmin.getId());

        logger.info("logout api,loginMallUser={}", loginAdmin.getId());

        //登出成功
        if (logoutResult) {
            return ResultGenerator.genSuccessResult();
        }
        //登出失败
        return ResultGenerator.genFailResult("logout error");
    }

    /*@PostMapping("/user/logoutC")
    @ApiOperation(value = "客户登出接口", notes = "清除token")
    public Result<String> logoutC(@TokenToUser Customer loginCustomer) {
        Boolean logoutResult = userService.logoutC(loginCustomer.getId());

        logger.info("logout api,loginMallUser={}", loginCustomer.getId());

        //登出成功
        if (logoutResult) {
            return ResultGenerator.genSuccessResult();
        }
        //登出失败
        return ResultGenerator.genFailResult("logout error");
    }*/

    @PostMapping("/user/logoutC")
    @ApiOperation(value = "客户登出接口", notes = "清除token")
    public Result<String> logoutC(@RequestBody @Valid UserParam userParam) {
        Customer loginCustomer = userService.getCDetail(userParam.getTelphone());
        Boolean logoutResult = userService.logoutC(loginCustomer.getId());

        logger.info("logout api,loginMallUser={}", loginCustomer.getId());

        //登出成功
        if (logoutResult) {
            return ResultGenerator.genSuccessResult();
        }
        //登出失败
        return ResultGenerator.genFailResult("logout error");
    }

    @PutMapping("/admin/info")
    @ApiOperation(value = "修改系统用户信息", notes = "")
    public Result updateAdminInfo(@RequestBody @ApiParam("系统用户信息") UserUpdateParam userUpdateParam, @TokenToUser Admin loginAdmin) {
        Boolean flag = userService.updateAdminInfo(userUpdateParam, loginAdmin.getId());
        if (flag) {
            //返回成功
            Result result = ResultGenerator.genSuccessResult();
            return result;
        } else {
            //返回失败
            Result result = ResultGenerator.genFailResult("修改失败");
            return result;
        }
    }

    @PutMapping("/customer/info")
    @ApiOperation(value = "修改客户信息", notes = "")
    public Result updateCustomerInfo(@RequestBody @ApiParam("客户信息") UserUpdateParam userUpdateParam) {
        Boolean flag = userService.updateCustomerInfo(userUpdateParam);
        if (flag) {
            //返回成功
            Result result = ResultGenerator.genSuccessResult();
            return result;
        } else {
            //返回失败
            Result result = ResultGenerator.genFailResult("修改失败");
            return result;
        }
    }

    @GetMapping("/admin/info")
    @ApiOperation(value = "获取系统用户信息", notes = "")
    public Result<UserVO> getAdminDetail(@TokenToUser Admin loginAdmin) {
        //已登录则直接返回
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(loginAdmin, userVO);
        return ResultGenerator.genSuccessResult(userVO);
    }

    /*@GetMapping("/customer/infoG")
    @ApiOperation(value = "获取客户信息", notes = "")
    public Result<UserVO> getAdminDetail(@TokenToUser Customer loginCustomer) {
        //已登录则直接返回
        log.info("hhh");
        UserVO userVO = new UserVO();
        userVO.setLoginName(loginCustomer.getCustomername());
        userVO.setTelphone(loginCustomer.getCustomertel());
        return ResultGenerator.genSuccessResult(userVO);
    }*/

    @PostMapping("/customer/infoG")
    @ApiOperation(value = "获取客户信息", notes = "")
    public Result<UserVO> getCustomerDetail(@RequestBody @Valid UserParam userParam) {
        //已登录则直接返回
        log.info(userParam.getTelphone());

        Customer customer = userService.getCDetail(userParam.getTelphone());        //想看看前端是否传过来token
        UserVO userVO = new UserVO();
        userVO.setLoginName(customer.getCustomername());
        userVO.setTelphone(customer.getCustomertel());
        return ResultGenerator.genSuccessResult(userVO);
    }

    @PostMapping("/customer/del")
    @ResponseBody
    public ResultData deleteUser(@RequestBody String id) throws JSONException {
        JSONArray jsonArray = null;
        jsonArray = new JSONArray("["+id+"]");
        System.out.println(jsonArray.getJSONObject(0).get("id"));
        String realId = jsonArray.getJSONObject(0).get("id").toString();
        Long uid = Long.valueOf(realId);
        this.userService.deleteCustomer(uid);
        return ResultData.success();
    }

    @PostMapping("/userAdd")
    @ResponseBody
    public ResultData addCustomer(@RequestBody UserInsertParam userInsertParam){
        //System.out.println(addressReq.getStreetName());
        //System.out.println(addressReq.getTel());
        // Address address = this.addressService.createOne(addressReq);
        Customer customer = this.userService.createOne(userInsertParam);
        // System.out.println(address.getStreetName());
        // System.out.println(address.getTel());
        return ResultData.success();
    }

    @PostMapping("/customer/udate")
    @ResponseBody
    public ResultData uodateCustomer(@RequestBody CustomerUpdateParam customerUpdateParam){
        //System.out.println(addressReq.getStreetName());
        //System.out.println(addressReq.getTel());
        // Address address = this.addressService.createOne(addressReq);
        this.userService.updateCustomer(customerUpdateParam);
        // System.out.println(address.getStreetName());
        // System.out.println(address.getTel());
        return ResultData.success();
    }

    @PostMapping("/customer/search")
    @ResponseBody
    public List<Customer> searchCustomer(@RequestBody SearchCustomerParam searchCustomerParam){
        //System.out.println(addressReq.getStreetName());
        //System.out.println(addressReq.getTel());
        // Address address = this.addressService.createOne(addressReq);
        String customerName = searchCustomerParam.getCustomerName();
        List<Customer> customers = new ArrayList<>();
        if(customerName.equals("")){
            customers = this.userService.getAll();
            return customers;
        }
        customers = this.userService.searchCustomer(customerName);
        // System.out.println(address.getStreetName());
        // System.out.println(address.getTel());
        return customers;
    }




}
